<script setup lang="ts">
import { computed, nextTick, ref, watch } from 'vue';
import { NCascader } from 'naive-ui';
import { InventoryGoods } from '@/service/api/inventory';
import { useAuthStore } from '@/store/modules/auth';
import type {
  CascaderOptionWithMeta,
  ClassSelectEmitData,
  GoodsClassSelectorEmits,
  GoodsClassSelectorProps,
  RawGoodsClassData
} from './types';

// Props默认值
const props = withDefaults(defineProps<GoodsClassSelectorProps>(), {
  modelValue: '',
  multiple: false,
  placeholder: '请选择商品分类',
  allowClear: true,
  disabled: false,
  size: 'small',
  showSearch: true,
  filterable: true,
  changeOnSelect: true
});

const emit = defineEmits<GoodsClassSelectorEmits>();

// 响应式数据
const authStore = useAuthStore();
const classOptions = ref<CascaderOptionWithMeta[]>([]);
const loading = ref(false);
const dataLoaded = ref(false);

// Select组件引用
const cascaderRef = ref<any>(null);
// 标记是否需要在数据加载完成后自动展开
const shouldAutoOpen = ref(false);

// Cascader 双向绑定的选中值
const cascaderValue = computed({
  get: (): string | string[] | string[][] | null => {
    if (!props.modelValue || classOptions.value.length === 0) {
      return null;
    }

    if (props.multiple) {
      // 多选模式：返回路径数组的数组
      const ids = Array.isArray(props.modelValue) ? props.modelValue : [];
      const paths = ids.map(id => findPathById(id, classOptions.value)).filter(path => path.length > 0);
      return paths.length > 0 ? paths : null;
    }
    // 单选模式：直接返回 objectId，NCascader 会自动处理
    return (props.modelValue as string) || null;
  },
  set: (value: string | string[] | string[][] | null) => {
    // v-model的set只负责更新modelValue，不处理业务逻辑
    // 业务逻辑在handleCascaderUpdateValue中处理
    if (!value) {
      emit('update:modelValue', props.multiple ? [] : '');
      return;
    }

    if (props.multiple && Array.isArray(value) && value.length > 0 && Array.isArray(value[0])) {
      // 多选模式：取每个路径的最后一个值
      const paths = value as string[][];
      const ids = paths.map(path => path[path.length - 1]);
      emit('update:modelValue', ids);
    } else if (!props.multiple && typeof value === 'string') {
      // 单选模式：直接使用字符串值
      emit('update:modelValue', value);
    } else if (!props.multiple && Array.isArray(value) && typeof value[0] === 'string') {
      // 单选模式：取路径的最后一个值
      const path = value as string[];
      const finalId = path[path.length - 1];
      emit('update:modelValue', finalId);
    }
  }
});

// 根据ID查找在树中的路径
const findPathById = (id: string, options: CascaderOptionWithMeta[], path: string[] = []): string[] => {
  for (const option of options) {
    const currentPath = [...path, option.value];

    if (option.value === id) {
      return currentPath;
    }

    if (option.children && option.children.length > 0) {
      const childPath = findPathById(id, option.children, currentPath);
      if (childPath.length > 0) {
        return childPath;
      }
    }
  }
  return [];
};

// 转换商品分类数据为Cascader格式
const transformClassData = (classList: RawGoodsClassData[]): CascaderOptionWithMeta[] => {
  if (!Array.isArray(classList)) return [];

  return classList.map(item => {
    const option: CascaderOptionWithMeta = {
      label: item.content,
      value: item.objectId,
      objectId: item.objectId,
      content: item.content,
      isLeaf: !item.goodClasses || item.goodClasses.length === 0
    };

    if (item.goodClasses && item.goodClasses.length > 0) {
      option.children = transformClassData(item.goodClasses);
      option.isLeaf = false;
    }

    return option;
  });
};

// 移除未使用的 loadData 函数

// 获取商品分类列表
const fetchClassList = async () => {
  if (loading.value || dataLoaded.value) return;

  loading.value = true;

  // 获取用户权限
  const rights = authStore.getInventoryRights();
  const seeRights = rights?.goodClass?.see || [];

  const response = await InventoryGoods.getGoodsClassList(seeRights);

  if (response && !response.error && response.data) {
    let classData = [];

    // 处理响应数据结构
    if (Array.isArray(response.data)) {
      classData = response.data;
    } else if (response.data.data && Array.isArray(response.data.data)) {
      classData = response.data.data;
    }

    // 转换为Cascader所需的格式
    const transformedData = transformClassData(classData);
    classOptions.value = transformedData;
    dataLoaded.value = true;
  } else {
    classOptions.value = [];
    dataLoaded.value = true;
  }

  loading.value = false;
};

// NCascader update:value 事件处理（只接收value参数）
const handleCascaderUpdateValue = (value: string | string[] | string[][] | null) => {
  let compatibleValue: string | string[] = '';
  let finalObjectId = '';
  let finalName = '';

  if (value) {
    if (props.multiple && Array.isArray(value) && value.length > 0 && Array.isArray(value[0])) {
      // 多选模式：value 是 string[][]，每个元素是一个路径
      const paths = value as string[][];
      compatibleValue = paths.map(path => path[path.length - 1]);
      if (paths.length > 0) {
        const firstPath = paths[0];
        finalObjectId = firstPath[firstPath.length - 1];
        const option = findOptionByValue(finalObjectId, classOptions.value);
        finalName = option?.content || '';
      }
    } else if (!props.multiple && typeof value === 'string') {
      // 单选模式：value 是 string，直接就是最终的 objectId
      finalObjectId = value;
      compatibleValue = finalObjectId;
      const option = findOptionByValue(finalObjectId, classOptions.value);
      finalName = option?.content || '';
    } else if (!props.multiple && Array.isArray(value) && typeof value[0] === 'string') {
      // 单选模式：value 是 string[]，是一个路径数组
      const path = value as string[];
      finalObjectId = path[path.length - 1];
      compatibleValue = finalObjectId;
      const option = findOptionByValue(finalObjectId, classOptions.value);
      finalName = option?.content || '';
    }
  }

  emit('change', compatibleValue, undefined);

  // 发送 selectClass 事件
  if (finalObjectId) {
    const emitData: ClassSelectEmitData = {
      name: finalName,
      objectId: finalObjectId,
      selected: props.multiple ? (Array.isArray(value) ? [value as string[]] : undefined) : undefined
    };

    emit('selectClass', emitData);
  } else {
    // 清空选择处理
    const emitData: ClassSelectEmitData = {
      name: '',
      objectId: '',
      selected: props.multiple ? [] : undefined
    };

    emit('selectClass', emitData);
  }
};

// 根据值查找选项
const findOptionByValue = (value: string, options: CascaderOptionWithMeta[]): CascaderOptionWithMeta | null => {
  for (const option of options) {
    if (option.value === value) {
      return option;
    }

    if (option.children && option.children.length > 0) {
      const childOption = findOptionByValue(value, option.children);
      if (childOption) {
        return childOption;
      }
    }
  }
  return null;
};

const handleFocus = () => {
  // 聚焦时加载数据
  if (!dataLoaded.value && !loading.value) {
    shouldAutoOpen.value = true;
    fetchClassList();
  }
};

const handleBlur = () => {
  // 可以在这里处理失焦事件
};

// 监听modelValue变化
watch(
  () => props.modelValue,
  () => {
    // 可以在这里处理modelValue变化
  },
  { immediate: true }
);

// 监听分类选项数据变化
watch(
  () => classOptions.value,
  newOptions => {
    if (shouldAutoOpen.value && newOptions.length > 0) {
      shouldAutoOpen.value = false;

      nextTick(() => {
        // 增强的重试机制
        const tryShow = (attempt = 1, maxAttempts = 3) => {
          setTimeout(
            () => {
              if (cascaderRef.value && typeof cascaderRef.value.show === 'function') {
                try {
                  cascaderRef.value.show();
                } catch (error) {
                  if (attempt < maxAttempts) {
                    tryShow(attempt + 1, maxAttempts);
                  }
                }
              } else if (attempt < maxAttempts) {
                tryShow(attempt + 1, maxAttempts);
              }
            },
            attempt === 1 ? 200 : 100 * attempt
          ); // 第一次200ms，后续递增延时
        };

        tryShow();
      });
    }
  },
  { deep: true }
);
</script>

<template>
  <div class="relative">
    <NCascader
      ref="cascaderRef"
      v-model:value="cascaderValue as any"
      :options="classOptions"
      :placeholder="loading ? '加载中...' : placeholder"
      :clearable="allowClear"
      :disabled="disabled || loading"
      :filterable="showSearch"
      :loading="loading"
      :cascade="false"
      :show-path="false"
      check-strategy="all"
      :change-on-select="true"
      expand-trigger="click"
      value-field="value"
      label-field="label"
      children-field="children"
      :style="{
        width: '140px !important',
        minWidth: '140px !important',
        maxWidth: '140px !important'
      }"
      @update:value="handleCascaderUpdateValue"
      @focus="handleFocus"
      @blur="handleBlur"
    />
  </div>
</template>

<style scoped></style>
